package com.example.headers.service;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:MessageService
 * Package:com.example.headers.service
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/8/11-20:51
 * @Version:v1.0
 */
@Service
@Slf4j
public class MessageService {

    @Resource
    private AmqpTemplate amqpTemplate;

    @Value("${my.exchangeName}")
    private String exchangeName;

    public void sendMsg() {
        MessageProperties messageProperties = new MessageProperties();
        Map<String, Object> headers = new HashMap<>();
        headers.put("type", "s");
        headers.put("status", 0);

        //设置消息头
        messageProperties.setHeaders(headers);
        //添加消息属性
        Message message = MessageBuilder
                .withBody("头部交换机".getBytes())
                .andProperties(messageProperties)
                .build();
        //头部交换机中路由key无所谓，用的是消息属性中的消息头
        amqpTemplate.convertAndSend(exchangeName, "", message);

        log.info("消息发送完毕，发送时间为：{}", new Date());
    }

}
